智能文章系统实战-Android文章客户端(8)

admin 发布于:2018-6-21 16:53  有 3031 人浏览,获得评论 0 条 标签: Android 

1. 列表模板XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.demo.article.MainActivity">

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

 

 

2.列表项模板

<?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">
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
    />
</LinearLayout>

 

3.文章类程序

public class Item {
    private int id;
	private String title;
    private String url;

    public Item(int id,String title, String url) {
        this.id = id;
        this.title = title;
		this.url = url;
    }

    public int getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }
	
	public String getUrl() {
        return url;
    }
}

 

 

4.数据适配器

public class ItemAdapter extends ArrayAdapter<Item> {
    private int layoutId;

    public ItemAdapter(Context context, int layoutId, List<Item> list) {
        super(context, layoutId, list);
        this.layoutId = layoutId;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        
        View view;
        ViewHolder viewHolder;
        Item item = getItem(position);
        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(layoutId, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.textView = (TextView) view.findViewById(R.id.title);
            view.setTag(viewHolder);
        } else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }
        viewHolder.textView.setText(item.getTitle());

        return view;
    }

    class ViewHolder {
        TextView textView;
    }
}

 

 

3.列表程序

public class MainActivity extends Activity {    
	private List<Item> list = new ArrayList<>();
	private ListView listView 
	private ItemAdapter<Item> itemAdapter;
    private ProgressDialog dialog;	
	
	@Override    
	protected void onCreate(Bundle savedInstanceState) {    
		super.onCreate(savedInstanceState);    
		setContentView(R.layout.activity_main);
		
		/*
		//初始化数据
		initList();
		
		//用自定义的数据适配器和自定义的布局显示列表
		ItemAdapter itemAdapter = new ItemAdapter(MainActivity.this, R.layout.item, list);    
		ListView listView = (ListView) findViewById(R.id.listview);    
		listView.setAdapter(itemAdapter);
		*/
		
		
		//进度条
		dialog = new ProgressDialog(MainActivity.this);
		
		//列表显示控件listView
		listView = (ListView) findViewById(R.id.listview); 
		
		//请求服务器获取数据,解析数据,加载列表
        new dataAsyncTask().execute("http://news.demo.com/app.php");
		
		

		//短暂点击跳到详情页
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				
				//详情页
				Item item = list.get(position);
				Intent intent = new Intent(MainActivity.this, ContentActivity.class);
				intent.putExtra("title",item.getTitle());
                intent.putExtra("url",item.getUrl());
                startActivity(intent);
				
			}
		});
		
		//长按Toast显示标题
		listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				Item item = list.get(position);
				Toast.makeText(MainActivity.this, "long click " + item.getTitle(), Toast.LENGTH_SHORT).show();

				return true;
			}
		});
	}

	//仅仅用来做测试,实际是对接的服务器接口的数据
    private void initList() {
        for (int i = 0; i < 100; i++) {
            //public Item(int id,String title, String url) 
			Item item = new Item(i,"T" + i, "#" + i);
            list.add(item);
        }
    }
	
	
	//解析JSON数据
    private List<Item> parseJSON(jsonStr)
        JSONObject obj = new JSONObject(jsonStr); //最外层的JSONObject对象
		String errCode = obj.getString("errCode");//通过errCode字段获取其所包含的字符串
		String errMsg =  obj.getString("errMsg"); //通过errMsg字段获取其所包含的字符串
		
        JSONArray array = obj.getJSONArray("data");
        for(int i = 0 ; i<array.length();i++){
            JSONObject jsonObj = array.getJSONObject(i); //索引值,获取数组中包含的值
			
			//System.out.println(jsonObj.getString("title"));
			
			//把即系的数据加载到列表里
			Item item = new Item(jsonObj.getInt("id"),jsonObj.getString("title"),jsonObj.getString("url"));
            list.add(item);

        }
		return list;
    }
	
	
	//请求服务器数据
    public String httpData(String path)
    {
        String result = "";
        HttpClient httpClient = new DefaultHttpClient();
        try
        {
            HttpPost httpPost = new HttpPost(path);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                HttpEntity httpEntity = httpResponse.getEntity();
                if(httpEntity != null)
                {
                    result = EntityUtils.toString(httpEntity, "utf-8");
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            httpClient.getConnectionManager().shutdown();
        }
        
        return result;
    }
	
	
	
	public class dataAsyncTask extends AsyncTask<String, Void, List<String>>
    {
        @Override
        protected void onPreExecute()
        {
			//预加载
            dialog.setTitle("提示信息");
            dialog.setMessage("loading......");
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.setCancelable(false);
			dialog.show();
        }
		
		
        @Override
        protected List<Item> doInBackground(String... params)
        {
			//后台解析数据
            List<Item> tempList = new ArrayList<Item>();
            String jsonStr = httpData(params[0]);
            //解析服务器端的json数据
            tempList = parseJSON(jsonStr);
			return tempList;
        }
		
        @Override
        protected void onPostExecute(List<Item> list)
        {
			//显示列表数据
			itemAdapter = new ItemAdapter(MainActivity.this, R.layout.item, list);    
			listView.setAdapter(itemAdapter);			
            dialog.dismiss();
        }
    }
	
	
	
	
		
}   

 

 

4.详细页模板

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/color_White">
    <WebView
        android:id="@+id/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
    />
		
</android.support.design.widget.CoordinatorLayout>

 

 

5.详细页程序

public class ContentActivity extends Activity {
    private WebView webView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content);

        

        webView = (WebView)findViewById(R.id.web_view);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());

        String url = getIntent().getStringExtra("url");
        //String title = getIntent().getStringExtra("title");
        webView.loadUrl(url);

    }
}

 

 6.  临时总结

暂时没有实现 下拉刷新,上拉加载更多数据,目前仅仅加载第1页的数据。后期优化。

adapter.setData(list);//刷新列表数据

adapter.notifyDataSetChanged();