我在我的活动中有4个LinearLayout我想获得点击布局的ID我怎么能得到它?![在此输入图像描述] [1]
观看网址图片:http://postimg.org/image/uq4hnmlkn/
LinearLayout lt = new LinearLayout(null);
lt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), String.valueOf(v.getId()),
Toast.LENGTH_LONG).show();
}
});
答案 0 :(得分:0)
尝试这种方式:
1。 Xml文件(activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/lnrMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"/>
2。 Java文件(MainActivity.java)
public class MainActivity extends Activity {
private LinearLayout lnrMain;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lnrMain = (LinearLayout) findViewById(R.id.lnrMain);
for (int i=1;i<5;i++){
LinearLayout layout = new LinearLayout(this);
layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout.setId(i);
TextView textView = new TextView(this);
textView.setText("Linear Layout "+i);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
layout.addView(textView);
layout.setTag(i);
layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"Linear Layout "+view.getTag()+" Is Clicked...",Toast.LENGTH_SHORT).show();
}
});
lnrMain.addView(layout);
}
}
}