我的移动后退按钮在Fragment中不起作用(android)

时间:2016-12-16 07:23:16

标签: android

我在android中创建了应用程序,当我使用活动我的移动按钮工作正常但是当我开始使用片段类时,我的移动后退按钮不起作用... 我需要在片段中编写任何代码吗? 这是我的片段代码: -

public class NewsDetailsFragment extends Fragment implements ApiListener {

    String album_name;
    String duration;
    String song_name;
    TextView localTextView1,localTextView2,localTextView3;
    ImageView image;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.activity_single_track,container,false);
        localTextView1 = (TextView) view.findViewById(R.id.song_title);
        localTextView2 = (TextView) view.findViewById(R.id.album_name);
        localTextView3 = (TextView) view.findViewById(R.id.duration);
        image = (ImageView) view.findViewById(R.id.img);
        API_GET_TRACK_DETAILS(CustomListAdapter.id + "");
        return  view;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            getActivity().finish();
        }

        return super.onOptionsItemSelected(item);
    }

    private void API_GET_TRACK_DETAILS(String product) {
        Map<String, String> params = new HashMap<>(2);
        params.put("song", product);
        JSONObjectCommonAPI api = new JSONObjectCommonAPI(getActivity(), "Loading...", false, UrlFactory.KHABAR_DETAIL_URL, params, 10);
        api.apiListener = NewsDetailsFragment.this;

    }

    @Override
    public void onSuccess(JSONObject jsonObject, int id) {

        if (id == 10) {

            song_name = jsonObject.optString("name");
            album_name = jsonObject.optString("album");
            duration = jsonObject.optString("duration");

            localTextView1.setText(song_name);
            Picasso.with(getActivity()).load(album_name).into(image);
            localTextView2.setText(Html.fromHtml("" + album_name));
            localTextView3.setText(Html.fromHtml("<b></b> " + duration));

        }
    }
}

1 个答案:

答案 0 :(得分:0)

fragment.getView().setFocusableInTouchMode(true);
fragment.getView().requestFocus();
fragment.getView().setOnKeyListener( new OnKeyListener()
{
    @Override
    public boolean onKey( View v, int keyCode, KeyEvent event )
    {
        if( keyCode == KeyEvent.KEYCODE_BACK )
        {
            return true;
        }
        return false;
    }
} );