简体   繁体   English

Android刷新按钮的最佳做法?

[英]Android refresh button best practices?

Hi Having an activity that loads a twitter feed. 嗨有一个加载Twitter提要的活动。
Android Twitter String to Json Array . Android Twitter字符串到Json数组

I'm wanting to put a refresh button at the top that when clicked reloads the data. 我想在顶部放置一个刷新按钮,当点击重新加载数据时。

so far i've got it to just reload the activity is this the best way of doing this? 到目前为止,我已经得到它只是重新加载活动这是这样做的最佳方式?

    package co.uk.fantasticmedia.TheEvoStikLeague;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;



import android.app.ListActivity;



public class TwitterActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

    setContentView(R.layout.twitteract);


    Button refresh = (Button) findViewById(R.id.btn_refresh);

    //Listening to button event
    refresh.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            //Starting a new Intent
            Intent reload = new Intent(getApplicationContext(), TwitterActivity.class);



            startActivity(reload);


        }
    });





     try{
            // Create a new HTTP Client
            DefaultHttpClient defaultClient = new DefaultHttpClient();
            // Setup the get request
            HttpGet httpGetRequest = new HttpGet("https://api.twitter.com/1/statuses/user_timeline.json?screen_name=evostikleague&count=10");

            // Execute the request in the client
            HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
            // Grab the response
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
            String json = reader.readLine();

            Log.v(json,"jsonfeed");




            List<String> items = new ArrayList<String>();

              //items.add(json);


            JSONArray jArray = new JSONArray(json);


            for (int i=0; i < jArray.length(); i++)
            {    JSONObject oneObject = jArray.getJSONObject(i);
                items.add(oneObject.getString("text"));
                 Log.i("items", "items");
            }

            setListAdapter ( new ArrayAdapter<String>(this, R.layout.single_item, items));
            ListView list = getListView();
            list.setTextFilterEnabled(true);


            list.setOnItemClickListener(new OnItemClickListener(){

                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                        long arg3) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getApplicationContext(), ((TextView) arg1).getText(),1000).show();
                }



            });


        } catch(Exception e){
            // In your production code handle any errors and catch the individual exceptions
            e.printStackTrace();
        }

    }

















    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == R.id.home) {

            startActivity(new Intent(TwitterActivity.this, HomeActivity.class));

            return(true);
      }


        if (item.getItemId() == R.id.match) {

            startActivity(new Intent(TwitterActivity.this, MatchActivity.class));

            return(true);
      }



        if (item.getItemId() == R.id.teams) {

            startActivity(new Intent(TwitterActivity.this, TeamsActivity.class));

            return(true);
      }



        if (item.getItemId() == R.id.twitter) {

            startActivity(new Intent(TwitterActivity.this, TwitterActivity.class));

            return(true);
      }

        if (item.getItemId() == R.id.info) {

            startActivity(new Intent(TwitterActivity.this, InfoActivity.class));

            return(true);
      }


        return(super.onOptionsItemSelected(item));


    }




}

Use Menus to provide Refresh option. 使用菜单提供“ 刷新”选项。 So when the user presses Menu button on phone, they can choose Refresh command to reload tweets 因此,当用户按下手机上的菜单按钮时,他们可以选择刷新命令来重新加载推文

can you post the rest of your activity? 你能发布剩余的活动吗? Especially the portion that you are using to load the list the first time. 特别是您第一次加载列表时使用的部分。

Probably it is unnecessary to restart the entire activity. 可能没有必要重新启动整个活动。 You just need to move the portion of your code that populates the list for you into its own method. 您只需将填充列表的代码部分移动到自己的方法中即可。 Then you can call that method when the user wants to refresh. 然后,您可以在用户想要刷新时调用该方法。

If nothing else you should change: 如果没有其他你应该改变:

 Intent reload = new Intent(getApplicationContext(), TwitterActivity.class);

to

Intent reload = new Intent(TwitterActivity.this, TwitterActivity.class);

EDIT: You need to move your try / catch block into a new method called refresh(). 编辑:您需要将try / catch块移动到名为refresh()的新方法中。 Then call that method anytime you want to reload the list. 然后在您想要重新加载列表的任何时候调用该方法。 like this: 像这样:

It would also be a bood idea to move your networking out of the main thread. 将您的网络移出主线程也是一个好主意。

public class TwitterActivity extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.twitteract);


    Button refresh = (Button) findViewById(R.id.btn_refresh);

    //Listening to button event
    refresh.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            refresh();


        }
    });



    refresh();



}

private void refresh(){

     try{
        // Create a new HTTP Client
        DefaultHttpClient defaultClient = new DefaultHttpClient();
        // Setup the get request
        HttpGet httpGetRequest = new HttpGet("https://api.twitter.com/1/statuses/user_timeline.json?screen_name=evostikleague&count=10");

        // Execute the request in the client
        HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
        // Grab the response
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
        String json = reader.readLine();

        Log.v(json,"jsonfeed");




        List<String> items = new ArrayList<String>();

          //items.add(json);


        JSONArray jArray = new JSONArray(json);


        for (int i=0; i < jArray.length(); i++)
        {    JSONObject oneObject = jArray.getJSONObject(i);
            items.add(oneObject.getString("text"));
             Log.i("items", "items");
        }

        setListAdapter ( new ArrayAdapter<String>(this, R.layout.single_item, items));
        ListView list = getListView();
        list.setTextFilterEnabled(true);


        list.setOnItemClickListener(new OnItemClickListener(){

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), ((TextView) arg1).getText(),1000).show();
            }



        });


    } catch(Exception e){
        // In your production code handle any errors and catch the individual exceptions
        e.printStackTrace();
    }




}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getItemId() == R.id.home) {

        startActivity(new Intent(TwitterActivity.this, HomeActivity.class));

        return(true);
  }


    if (item.getItemId() == R.id.match) {

        startActivity(new Intent(TwitterActivity.this, MatchActivity.class));

        return(true);
  }



    if (item.getItemId() == R.id.teams) {

        startActivity(new Intent(TwitterActivity.this, TeamsActivity.class));

        return(true);
  }



    if (item.getItemId() == R.id.twitter) {

        startActivity(new Intent(TwitterActivity.this, TwitterActivity.class));

        return(true);
  }

    if (item.getItemId() == R.id.info) {

        startActivity(new Intent(TwitterActivity.this, InfoActivity.class));

        return(true);
  }


    return(super.onOptionsItemSelected(item));


}

}

This is more archaic refresh button but I work well in my application. 这是更古老的刷新按钮,但我在我的应用程序中运行良好。

public void refresh(View view){          //refresh is onClick name
    onRestart();
}

@Override
protected void onRestart() {

    // TODO Auto-generated method stub
    super.onRestart();
    Intent i = new Intent(lala.this, lala.class);  //your class
    startActivity(i);
    finish();

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM