我希望为程序创建的布局中的一些视图(如textview,imageview等)分配ID。那么最好的设置ID的方式是什么。
我希望为程序创建的布局中的一些视图(如textview,imageview等)分配ID。那么最好的设置ID的方式是什么。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="id" name="layout1" />
<item type="id" name="layout2" />
<item type="id" name="layout3" />
</resources>
现在,对于您动态创建的布局或视图,您可以像下面这样使用这些id:
new_layout1.setId(R.id.layout1);
new_view2.setId(R.id.layout2);
new_layout3.setId(R.id.layout3);
希望这能对你有所帮助。
谷歌终于意识到了为编程创建的视图生成唯一ID的必要性......
从API级别17开始,可以像这样使用View.generateViewId():
view.setId(View.generateViewId());
对于目标 API 级别为 16 或更低的应用程序,请改用 ViewCompat.generateViewId()
:
view.setId(ViewCompat.generateViewId());
ViewCompat.generateViewId()
。 - Hirbod Behnam创建文件夹 res/values/ids.xml
并
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="refresh" type="id"/>
<item name="settings" type="id"/>
</resources>
在 Activity 类中可以这样调用:
ImageView refreshImg = new ImageView(activity);
ImageView settingsImg = new ImageView(activity);
refreshImg.setId(R.id.refresh);
settingsImg .setId(R.id.settings);
res/values/ids.xml
的方法是: - Bugs Happen这样做是行不通的:
layout.setId(100);
但是,这样会:
int id=100;
layout.setId(id);
还有一个(摘自Aaron Dougherty):
layout.setId(100+1);
ViewCompat.generateViewId()
<LinearLayout>
<ImageView>
<TextView>
<Button>
<ImageView>
<TextView>
<Button>
<ImageView>
<TextView>
<Button>
...
</LinearLayout>
for(int i=0;i<totalGroups;i++)
{
ImageView img;
TextView tv;
Button b;
... // set other properties of above components
img.setId(i);
tv.setId(i);
b.setId(i);
... //handle all events on these components here only
... //add all components to your main layout
}
如果只想添加一个组件组,您可以使用任何大的整数编号,不会与资源中其他组件的编号冲突。这样不会有太多的冲突。
我用了一种不同的方法。
创建了自己的R.id HashMap。
然后使用该值作为view.setID()部分的ID。
字符串是ID,整数是其值。
Private HashMap<String, Integer> idMap= new HashMap<String, Integer>();
private int getRandomId(){
boolean notInGeneralResourses = false;
boolean foundInIdMap = false;
String packageName = mainActivity.getPackageName();
Random rnd = new Random();
String name ="";
//Repaet loop in case random number already exists
while(true) {
// Step 1 - generate a random id
int generated_id = rnd.nextInt(999999);
// Step 2 - Check R.id
try{
name = mainActivity.getResources().getResourceName(generated_id);
}catch(Exception e){
name = null;
}
notInGeneralResourses = false;
if (name == null || !name.startsWith(packageName)) {
notInGeneralResourses = true;
}else{
notInGeneralResourses = false;
localLog("Found in R.id list.");
}
// Step 3 - Check in id HashMap
if(notInGeneralResourses){
List<Integer> valueList = new ArrayList<Integer>(idMap.values());
foundInIdMap = false;
for (Integer value : valueList) {
if (generated_id == value) {
foundInIdMap = true;
localLog("Found in idMAp.");
}
}
}
// Step 4 - Return ID, or loop again.
if (!foundInIdMap) {
localLog("ID clear for use. "+generated_id);
return generated_id;
}
}
}
并设置:
String idName = "someName";
int generated_R_id = getRandomId();
idMap.put(idName,generated_R_id);
someView.setId(idMap.get(idName));
ImageView test = (ImageView)
mainActivity.findViewById(idMap.get("somName"));
并测试它 -
test.setImageResource(R.drawable.differentPic);
附注:我这样写是为了方便解释。
显然,它可以更好地书写并更紧凑。
试试这段代码!这应该能帮助你有一个想法。
activity_prac_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:text="@string/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/display_txt"
android:textStyle="bold"
android:textSize="18sp"
android:textAlignment="center"
android:layout_gravity="center_horizontal"/>
<GridLayout
android:id="@+id/my_grid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:rowCount="4">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/linear_view">
<Button
android:text="@string/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/my_btn"
android:layout_gravity="center_horizontal"/>
<TextView
android:text="@string/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/my_txt"
android:textSize="18sp"
/>
</LinearLayout>
</GridLayout>
</LinearLayout>
这是代码的其余部分
public class AnotherActivity extends AppCompatActivity {
private int count = 1;
List<Integer> gridArray;
private TextView myDisplayText;
@Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gridArray = new ArrayList<>();
gridArray.add(Integer.valueOf(1));
setContentView(R.layout.activity_prac_main);
findViews();
}
private void findViews(){
GridLayout gridLayout = (GridLayout)findViewById(R.id.my_grid);
gridLayout.setColumnCount(4);
LinearLayout linearLayout = (LinearLayout) gridLayout.findViewById(R.id.linear_view);
linearLayout.setTag("1");
Button myButton = (Button) linearLayout.findViewById(R.id.my_btn);
myButton.setTag("1");
TextView myText = (TextView) linearLayout.findViewById(R.id.my_txt);
myText.setText("1");
myDisplayText = (TextView) findViewById(R.id.display_txt);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TextView txt = (TextView) view;
myDisplayText.setText("PRESS " + txt.getTag().toString());
if(count < 24) {
createView();
}
else{
dialogBox();
}
}
});
}
private void createView(){
LinearLayout ll = new LinearLayout(this);
ll.setId(Integer.valueOf(R.id.new_view_id));
ll.setTag(String.valueOf(count+1));
Button newBtn = createButton();
newBtn.setId(Integer.valueOf(R.id.new_btn_id));
newBtn.setTag(String.valueOf(count+1));
TextView txtView = createText();
txtView.setId(Integer.valueOf(R.id.new_txt_id));
txtView.setTag(String.valueOf(count+1));
txtView.setText(String.valueOf(count+1));
GridLayout gridLayout = (GridLayout)findViewById(R.id.my_grid);
ll.addView(newBtn);
ll.addView(txtView);
ll.setOrientation(LinearLayout.VERTICAL);
gridLayout.addView(ll);
count++;
}
private Button createButton(){
Button myBtn = new Button(this);
myBtn.setText(R.string.button_send);
myBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TextView txt = (TextView) view;
myDisplayText.setText("PRESS " + txt.getTag().toString());
if(count < 24) {
createView();
}
else{
dialogBox();
}
}
});
return myBtn;
}
public void dialogBox() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GRID IS FULL!");
alertDialogBuilder.setPositiveButton("DELETE",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
GridLayout gridLayout = (GridLayout)findViewById(R.id.my_grid);
gridLayout.removeAllViews();
count = 0;
createView();
}
});
alertDialogBuilder.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private TextView createText(){
TextView myTxt = new TextView(this);
myTxt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
return myTxt;
}
}
正如您所看到的,ids 是在 res -> values -> ids 文件中创建的。
动态创建视图时,id 对于视图是相同的。
每个 TextView 共享相同的 id。每个 Button 共享相同的 id。每个布局共享相同的 id。
Ids 只对访问视图内容很重要。
然而,标签是使每个视图彼此独特的东西。
希望这可以帮助您!
你所需要做的就是调用 ViewCompat.generateViewId()
例如:
val textView = TextView(this)
textView.text = "Hello World"
textView.setLayoutParams(ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
textView.id = ViewCompat.generateViewId()
您可以将您的ID定义为资源,然后使用视图的setId()
方法来设置它。
在XML文件中,可以这样定义ID:
<resources>
<item type="id">your id name</item>
</resources>
然后,在Java文件中使用...
layout.setId(R.id.<your id name>)