作者通过Java代码来实现布局,而我习惯通过.xml文件来实现,所以我对程序做了如下修改
MainActivity.java
-
public class MainActivity extends Activity
-
{
-
ListView myList;
-
TextView textView;
-
LayoutInflater inflater=null;
-
@Override
-
public void onCreate(Bundle savedInstanceState)
-
{
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.activity_main1);
-
myList = (ListView) findViewById(R.id.myList);
-
BaseAdapter adapter = new BaseAdapter()
-
{
-
@Override
-
public int getCount()
-
{
-
// 指定一共包含40个选项
-
return 40;
-
}
-
@Override
-
public Object getItem(int position)
-
{
-
return null;
-
}
-
// 重写该方法,该方法的返回值将作为列表项的ID
-
@Override
-
public long getItemId(int position)
-
{
-
return position;
-
}
-
// 重写该方法,该方法返回的View将作为列表框
-
@Override
-
public View getView(int position, View convertView , ViewGroup parent)
-
{
-
// 创建一个LinearLayout,并向其中添加两个组件 Java代码
-
// LinearLayout line = new LinearLayout(MainActivity.this);
-
// line.setOrientation(0);
-
// ImageView image = new ImageView(MainActivity.this);
-
// image.setImageResource(R.drawable.tiger);
-
// TextView text = new TextView(MainActivity.this);
-
// text.setText("第" + (position +1 ) + "个列表项");
-
// text.setTextSize(20);
-
// text.setTextColor(Color.RED);
-
// line.addView(image);
-
// line.addView(text);
-
inflater = LayoutInflater.from(MainActivity.this);
-
if (convertView == null) {
-
convertView = inflater.inflate(R.layout.linearlayout1,null);
-
}
-
textView = (TextView) convertView.findViewById(R.id.tex);
-
textView.setText("第" + (position +1 ) + "个列表项");
-
// 返回LinearLayout实例
-
return convertView;
-
}
-
};
-
myList.setAdapter(adapter);
-
}
-
}
|
XML文件
-
<?xml version="1.0" encoding="utf-8"?>
-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-
android:orientation="vertical"
-
android:layout_width="match_parent"
-
android:layout_height="match_parent">
-
<ListView
-
android:id="@+id/myList"
-
android:layout_width="match_parent"
-
android:layout_height="match_parent"/>
-
</LinearLayout>
linearlayout1.xml
-
<?xml version="1.0" encoding="utf-8"?>
-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-
android:orientation="horizontal"
-
android:layout_width="match_parent"
-
android:layout_height="match_parent">
-
-
<ImageView
-
android:id="@+id/img"
-
android:src="@drawable/tiger"
-
android:layout_width="wrap_content"
-
android:layout_height="wrap_content"/>
-
-
<TextView
-
android:id="@+id/tex"
-
-
android:textSize="20dp"
-
android:textColor="@android:color/holo_red_light"
-
android:layout_width="wrap_content"
-
android:layout_height="wrap_content"/>
-
-
-
</LinearLayout>
|
效果: