android高级编程学习笔记--ToDoList第二版

(重点关注Fragment)

1. 在SDK中建立一个新的名为ToDoList2的Android Application工程;


2. 在res/layout文件夹下创建一个新的布局文件new_item_fragment.xml,该文件包含一个EditText节点,输入以下内容:

<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/addItemHint"
	/>

注意要在res/values/strings.xml中添加addItemHint的定义:

<string name="addItemHint">New To Do Item</string>


3. 创建一个NewItemFragment类,该类继承于Fragment:

在src目录上点击右键-->New-->Class,在Name栏输入NewItemFragment,然后点击Finish。

在新创建的NewItemFragment.java中输入以下内容:

NewItemFragment.java:

package com.example.todolist2;

import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

/* myself fragment*/
public class NewItemFragment extends Fragment{
	
	private OnNewItemAddedListener onNewItemAddedListener;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.new_item_fragment, container, false);
        
        final EditText myEditText = (EditText)rootView.findViewById(R.id.myEditText);
        
        myEditText.setOnKeyListener(new View.OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == KeyEvent.ACTION_DOWN)
				{
					if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER ||
							keyCode == KeyEvent.KEYCODE_ENTER)
					{
						String newItem = myEditText.getText().toString();
						onNewItemAddedListener.onNewItemAdded(newItem);
						myEditText.setText("");
						return true;
					}
				}
				return false;
			}
		});
    
        return rootView;
    }
	
    @Override
    public void onAttach(Activity activity)
    {
    	super.onAttach(activity);
    	try {
    	onNewItemAddedListener = (OnNewItemAddedListener)activity;
    	} catch (ClassCastException e) {
    		throw new ClassCastException(activity.toString() + " must implement OnNewItemAddedListente");
    	}
    	
    }
    
	public interface OnNewItemAddedListener{
		public void onNewItemAdded(String newItem);
	}
}
分析:

a. 该类的onCreateView填充了一个new_item_fragment布局(第一步中说创建),并实现了该布局中EditText对象的按键监听事件setOnKeyListener();

b. 该类定义了一个接口OnNewItemAddedListener(用于接受to-do事项并添加到列表中),主界面通过实现该接口来监听新事项的添加;

c. 该类包含了一个OnNewItemAddedListener对象onNewItemAddedListener,这个变量用于在父Activity绑定到该Fragment时(onAttach方法)保存实现了这个接口的父Activity类的引用。


4. 创建一个ToDoListFragment类,用于包含to-do事项列表:

在src目录上点击右键-->New-->Class,在Name栏输入ToDoListFragment,然后点击Finish。

在新创建的ToDoListFragment.java中输入以下内容:

ToDoListFragment.java:

package com.example.todolist2;

import android.app.ListFragment;

public class ToDoListFragment extends ListFragment {

}

备注: ListFragment包含一个ListView。


5. 在res/layout文件夹下创建一个新的布局文件todolist2_main.xml,输入以下内容:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <fragment android:name="com.example.todolist2.NewItemFragment"
        android:id="@+id/NewItemFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    
    <fragment android:name="com.example.todolist2.ToDoListFragment"
        android:id="@+id/ToDoListFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

</LinearLayout>


6. 修改MainActivity.java,修改后的文件内容为:

package com.example.todolist2;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
import android.app.FragmentManager;

public class MainActivity extends Activity 
	implements NewItemFragment.OnNewItemAddedListener{

	private ArrayAdapter<String> aa;
	private ArrayList<String> todoItems;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.todolist2_main); // 使用5中创建的布局
        FragmentManager fm = getFragmentManager();
        ToDoListFragment  todoListFragment = (ToDoListFragment)fm.findFragmentById(R.id.ToDoListFragment);
        // 创建ArrayAdapter并将其绑定到listview上
        todoItems = new ArrayList<String>();
        aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems);
        
        todoListFragment.setListAdapter(aa);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view. 
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }
    // 实现onNewItemAdded接口,接收收到的字符串变量并将其添加到ArrayList中
    public void onNewItemAdded(String newItem)
    {
    	todoItems.add(newItem);
    	aa.notifyDataSetChanged();
    }
}



你可能感兴趣的:(android高级编程学习笔记--ToDoList第二版)