view和viewGroup的区别
View只能操作自己
View只能操作自己
viewGroup能操作自己也可以操作孩子(就是抱在布局中的控件)
代码:
public class MainActivity extends Activity implements View.OnClickListener{
private LinearLayout linearLayout1;
private Button btn1;
private ImageView iv1;
private ImageView iv2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
}
/**
* 初始化控件
*/
private void findViews() {
linearLayout1 = (LinearLayout)findViewById( R.id.linearLayout1 );
btn1 = (Button)findViewById( R.id.btn1 );
iv1 = (ImageView)findViewById( R.id.iv1 );
iv2 = (ImageView)findViewById( R.id.iv2 );
btn1.setOnClickListener( this );
iv1.setOnClickListener( this );
iv2.setOnClickListener( this );
}
/**
* 点击事件
*/
@Override
public void onClick(View v) {
if ( v == btn1 ) {
show1(linearLayout1);
show2(linearLayout1);
}
}
/**
* View只能操作自己
*/
public void show1(View view) {
Log.e("111","linearLayout1>>>"+view.getId());
}
/**
* ViewGroup可以操作孩子
*/
public void show2(ViewGroup viewGroup) {
for(int i = 0; i <viewGroup.getChildCount() ; i++) {
Log.e("111","拿到布局中的孩子"+viewGroup.getChildAt(i).getId());
}
}
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mytest.MainActivity"
android:orientation="vertical"
android:id="@+id/linearLayout1"
android:background="#FF66FF"
>
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="按钮"
/>
<ImageView
android:id="@+id/iv1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:src="@mipmap/ic_launcher"
/>
<ImageView
android:id="@+id/iv2"
android:layout_width="match_parent"
android:layout_height="50dp"
android:src="@mipmap/ic_launcher"
/>
</LinearLayout>
源码下载:
Myjstojava ---- mytest
http://download.csdn.net/download/zhaihaohao1/10020298