我有一个Activity,它实现了View.OnClickListener
以及来自不同类的其他几个抽象方法。问题是全局onClick
没有被触发。
我必须手动为每个单独的视图设置一个新的OnClickListener,我无法在我的代码中找到Click事件被消耗的位置,并且无法传播到onClick(View view)
方法。
这是我活动的主体:
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.imnumbers.imnumbers.R;
import com.imnumbers.imnumbers.util.ApiResponse;
import com.imnumbers.imnumbers.util.Cache;
import com.imnumbers.imnumbers.util.CustomToast;
import com.imnumbers.imnumbers.util.Feed;
import com.imnumbers.imnumbers.util.MultipartUtility;
import com.imnumbers.imnumbers.util.ProfilesSingleton;
import com.imnumbers.imnumbers.util.Util;
import com.imnumbers.imnumbers.widget.ObservableScrollView;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
import de.hdodenhof.circleimageview.CircleImageView;
public class FeedsActivity extends ActionBarActivity
implements View.OnClickListener, NavigationDrawerFragment.NavigationDrawerCallbacks, NavigationDrawerFragmentRight.NavigationDrawerCallbacks,
ObservableScrollView.Callbacks, FeedsHeadFragment.OnFragmentInteractionListener, SwipeRefreshLayout.OnRefreshListener {
private static final int STATE_ONSCREEN = 0;
private int mState = STATE_ONSCREEN;
private static final int STATE_OFFSCREEN = 1;
private static final int STATE_RETURNING = 2;
private final int PANEL_STATUS_OPEN = 1;
private final int PANEL_STATUS_CLOSED = 0;
private int morePanelStatus = PANEL_STATUS_CLOSED;
AQuery aq;
String last_time_modified = "0";
boolean getting_feeds = false;
boolean first_time = true;
ArrayList<Feed> feeds;
@InjectView(R.id.feedLoader)
ProgressBar feedLoader;
@InjectView(R.id.feedsListView)
LinearLayout feedContainer;
@InjectView(R.id.pullToRWrapper)
LinearLayout pullToRWrapper;
@InjectView(R.id.pullToRText)
TextView pullToRText;
@InjectView(R.id.retryBtn)
TextView retryBtn;
@InjectView(R.id.menuLayout)
LinearLayout menuBtn;
@InjectView(R.id.moreBtn)
ImageView moreBtn;
@InjectView(R.id.morePanel)
RelativeLayout morePanel;
@InjectView(R.id.changeCoverWrapper)
LinearLayout changeCoverWrapper;
@InjectView(R.id.changeProfilePhotoWrapper)
LinearLayout changeProfilePhotoWrapper;
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
private NavigationDrawerFragmentRight mNavigationDrawerFragmentRight;
private ObservableScrollView mObservableScrollView;
private RelativeLayout mQuickReturnView;
private View mPlaceholderView;
private ScrollSettleHandler mScrollSettleHandler = new ScrollSettleHandler();
private int mMinRawY = 0;
private int mQuickReturnHeight;
private int mMaxScrollY;
private Context c;
private LayoutInflater inflater;
private float lastY;
private int Y;
private boolean refresh = false;
private SwipeRefreshLayout swipeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feeds);
getSupportActionBar().hide();
ButterKnife.inject(this);
c = this;
aq = new AQuery(c);
feeds = new ArrayList<Feed>();
last_time_modified = "0";
first_time = true;
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
// Navigation Drawers
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mNavigationDrawerFragmentRight = (NavigationDrawerFragmentRight)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer_right);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
mNavigationDrawerFragmentRight.setUp(
R.id.navigation_drawer_right,
(DrawerLayout) findViewById(R.id.drawer_layout));
// End - Navigation Drawers
mObservableScrollView = (ObservableScrollView) findViewById(R.id.oscrollview);
mObservableScrollView.setCallbacks(this);
mQuickReturnView = (RelativeLayout) findViewById(R.id.head);
mPlaceholderView = findViewById(R.id.place_holder);
mObservableScrollView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
onScrollChanged(mObservableScrollView.getScrollY());
mMaxScrollY = mObservableScrollView.computeVerticalScrollRange()
- mObservableScrollView.getHeight();
mQuickReturnHeight = mQuickReturnView.getHeight();
}
});
setOnClicks();
ViewHelper.setScaleX(morePanel, 2);
ViewHelper.setScaleY(morePanel, 2);
ViewHelper.setAlpha(morePanel, 0);
if (!Util.isNetworkAvailable(c)) {
CustomToast.makeToast(c, CustomToast.TYPE_ALERT, c.getString(R.string.no_internet_connection), Toast.LENGTH_SHORT);
}
new GetFeedsAsyncTask(ProfilesSingleton.getInstance().getCurrentProfile().getProfileID(), 0).execute();
}
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.feeds, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onScrollChanged(int scrollY) {
scrollY = Math.min(mMaxScrollY, scrollY);
mScrollSettleHandler.onScroll(scrollY);
int rawY = mPlaceholderView.getTop() - scrollY;
int translationY = 0;
switch (mState) {
case STATE_OFFSCREEN:
if (rawY <= mMinRawY) {
mMinRawY = rawY;
} else {
mState = STATE_RETURNING;
}
translationY = rawY;
break;
case STATE_ONSCREEN:
if (rawY < -mQuickReturnHeight) {
mState = STATE_OFFSCREEN;
mMinRawY = rawY;
}
translationY = rawY;
break;
case STATE_RETURNING:
translationY = (rawY - mMinRawY) - mQuickReturnHeight;
if (translationY > 0) {
translationY = 0;
mMinRawY = rawY - mQuickReturnHeight;
}
if (rawY > 0) {
mState = STATE_ONSCREEN;
translationY = rawY;
}
if (translationY < -mQuickReturnHeight) {
mState = STATE_OFFSCREEN;
mMinRawY = rawY;
}
break;
}
ViewPropertyAnimator.animate(mQuickReturnView).cancel();
ViewHelper.setTranslationY(mQuickReturnView, translationY + scrollY);
Y = scrollY;
}
@Override
public void onDownMotionEvent() {
mScrollSettleHandler.setSettleEnabled(false);
}
@Override
public void onUpOrCancelMotionEvent() {
mScrollSettleHandler.setSettleEnabled(true);
mScrollSettleHandler.onScroll(mObservableScrollView.getScrollY());
}
@Override
public void onFragmentInteraction(Uri uri) {
}
public JSONArray getFeeds(boolean forceRefresh, int profileID, int lastFeedTime) throws IOException, JSONException {
if (!forceRefresh || !Util.isNetworkAvailable(c)) {
String cache = Cache.readFromCache(c, "feeds");
if (!cache.equals("")) {
try {
JSONArray ja = new JSONArray(cache);
return ja;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
getting_feeds = true;
JSONArray feedsArray = null;
try {
MultipartUtility multipart = new MultipartUtility(Util.URL_GET_FEEDS, "UTF-8");
multipart.addFormField("profile_id",
String.valueOf(profileID));
List<String> response = multipart.finish();
ApiResponse responseObject = new ApiResponse(response.get(0));
if (responseObject.isSuccessful()) {
feedsArray = responseObject.getDataJSONArray();
} else {
CustomToast.makeToast(c, CustomToast.TYPE_ALERT, c.getString(R.string.unknown_error), CustomToast.LENGTH_SHORT);
}
} catch (IOException ex) {
ex.printStackTrace();
}
return feedsArray;
}
private void showFeeds(final JSONArray array) {
feedLoader.setVisibility(View.GONE);
feedContainer.setVisibility(View.VISIBLE);
feedContainer.removeAllViews();
//if (first_time) {
for (int i = 0; i < array.length(); i++) {
inflater = (LayoutInflater) c.getSystemService(c.LAYOUT_INFLATER_SERVICE);
final View feedView = inflater.inflate(R.layout.feed_layout, feedContainer, false);
final Feed feed;
try {
feed = new Feed(array.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
return;
}
final int position = i;
@SuppressLint("WrongViewCast") CircleImageView avatar = (CircleImageView) feedView.findViewById(R.id.avatar);
aq.id(avatar).image(feed.getProfile().getPhotoFullPath(), false, true, 50, R.drawable.avatar);
TextView username = (TextView) feedView.findViewById(R.id.username);
final Feed finalFeed = feed;
username.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent profile = new Intent(c, SingleProfileActivity.class);
int profileID = finalFeed.getProfile().getProfileID();
profile.putExtra("profile_id", profileID);
startActivity(profile);
}
});
TextView date = (TextView) feedView.findViewById(R.id.feed_date);
ViewStub feedContent = (ViewStub) feedView.findViewById(R.id.feed_content);
View content;
switch (feed.getType()) {
case "photo":
feedContent.setLayoutResource(R.layout.feed_content_photo);
content = feedContent.inflate();
ImageView feedPhoto = (ImageView) content.findViewById(R.id.feed_pic);
aq.id(feedPhoto).image(Util.URL_FEEDS_PHOTOS + feed.getPhotoPath(), false, true, 0, 0, null, 0, AQuery.RATIO_PRESERVE);
break;
default:
case "simple":
feedContent.setLayoutResource(R.layout.feed_content_simple);
content = feedContent.inflate();
break;
case "aparat":
case "music":
continue;
}
RelativeLayout commentsWrapper = (RelativeLayout) feedView.findViewById(R.id.feed_comments);
commentsWrapper.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int pos = position;
Intent singleFeedActivity = new Intent(c, SingleFeedActivity.class);
singleFeedActivity.putExtra("feed_position", pos);
singleFeedActivity.putExtra("feeds", array.toString());
startActivity(singleFeedActivity);
}
});
TextView feed_text = (TextView) content.findViewById(R.id.feed_text);
username.setText(feed.getProfile().getFirstName() + " " + feed.getProfile().getLastName());
date.setText(String.valueOf(feed.getTimeCreated()));
feed_text.setText(Html.fromHtml(feed.getText()));
((TextView) feedView.findViewById(R.id.likesCountText)).setText(String.valueOf(feed.getLikesCount()));
feedContainer.addView(feedView);
}
if (feedContainer.getVisibility() == View.GONE) {
feedContainer.setVisibility(View.VISIBLE);
}
getting_feeds = false;
}
public void goToPostActivity(View view) {
Intent postActivity = new Intent(this, PostFeedActivity.class);
startActivity(postActivity);
}
@Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
swipeLayout.setRefreshing(false);
}
}, 5000);
// CustomToast.makeToast(c, CustomToast.TYPE_DEFAULT, "refreshing", CustomToast.LENGTH_SHORT);
Log.d("Refresh", "Doing Refresh!");
new GetFeedsAsyncTask(ProfilesSingleton.getInstance().getCurrentProfile().getProfileID(), 0).execute();
}
public void setOnClicks() {
menuBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
((DrawerLayout) findViewById(R.id.drawer_layout)).openDrawer(mNavigationDrawerFragment.getView());
}
});
moreBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (morePanelStatus) {
case PANEL_STATUS_OPEN:
ViewPropertyAnimator.animate(morePanel).scaleX(1);
ViewPropertyAnimator.animate(morePanel).scaleY(1);
ViewPropertyAnimator.animate(morePanel).alpha(1);
/* ViewPropertyAnimator.animate(changeCoverWrapper).scaleX(1);
ViewPropertyAnimator.animate(changeCoverWrapper).scaleY(1);
ViewPropertyAnimator.animate(changeCoverWrapper).alpha(1);
ViewPropertyAnimator.animate(changeProfilePhotoWrapper).scaleX(1);
ViewPropertyAnimator.animate(changeProfilePhotoWrapper).scaleY(1);
ViewPropertyAnimator.animate(changeProfilePhotoWrapper).alpha(1);*/
morePanelStatus = PANEL_STATUS_CLOSED;
break;
case PANEL_STATUS_CLOSED:
ViewPropertyAnimator.animate(morePanel).scaleX(2);
ViewPropertyAnimator.animate(morePanel).scaleY(2);
ViewPropertyAnimator.animate(morePanel).alpha(0);
/* ViewPropertyAnimator.animate(changeCoverWrapper).scaleX(3);
ViewPropertyAnimator.animate(changeCoverWrapper).scaleY(3);
ViewPropertyAnimator.animate(changeCoverWrapper).alpha(0);
ViewPropertyAnimator.animate(changeProfilePhotoWrapper).scaleX(3);
ViewPropertyAnimator.animate(changeProfilePhotoWrapper).scaleY(3);
ViewPropertyAnimator.animate(changeProfilePhotoWrapper).alpha(0);*/
morePanelStatus = PANEL_STATUS_OPEN;
break;
}
}
});
retryBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new GetFeedsAsyncTask(ProfilesSingleton.getInstance().getCurrentProfile().getProfileID(), 0).execute();
}
});
}
@Override
public void onClick(View view) {
Log.d("Global Click", "click"+ view.getId());
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_feeds, container, false);
return rootView;
}
}
private class ScrollSettleHandler extends Handler {
private static final int SETTLE_DELAY_MILLIS = 100;
private int mSettledScrollY = Integer.MIN_VALUE;
private boolean mSettleEnabled;
public void onScroll(int scrollY) {
if (mSettledScrollY != scrollY) {
// Clear any pending messages and post delayed
removeMessages(0);
sendEmptyMessageDelayed(0, SETTLE_DELAY_MILLIS);
mSettledScrollY = scrollY;
}
}
public void setSettleEnabled(boolean settleEnabled) {
mSettleEnabled = settleEnabled;
}
@Override
public void handleMessage(Message msg) {
// Handle the scroll settling.
if (STATE_RETURNING == mState && mSettleEnabled) {
int mDestTranslationY;
if (mSettledScrollY - ViewHelper.getTranslationY(mQuickReturnView) > mQuickReturnHeight / 2) {
mState = STATE_OFFSCREEN;
mDestTranslationY = Math.max(
mSettledScrollY - mQuickReturnHeight,
mPlaceholderView.getTop());
} else {
mDestTranslationY = mSettledScrollY;
}
mMinRawY = mPlaceholderView.getTop() - mQuickReturnHeight - mDestTranslationY;
ViewPropertyAnimator.animate(mQuickReturnView).translationY(mDestTranslationY);
}
mSettledScrollY = Integer.MIN_VALUE; // reset
}
}
public class GetFeedsAsyncTask extends AsyncTask<String, Void, Integer> {
int profileID, lastFeedTime;
JSONArray feedsArray;
public GetFeedsAsyncTask(int profileID, int lastFeedTime) {
this.profileID = profileID;
this.lastFeedTime = lastFeedTime;
}
@Override
protected Integer doInBackground(String... strings) {
try {
feedsArray = getFeeds(true, profileID, lastFeedTime);
return 1;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
@Override
protected void onPostExecute(Integer param) {
swipeLayout.setRefreshing(false);
if (param == 1) {
showFeeds(feedsArray);
feedLoader.setVisibility(View.GONE);
feedContainer.setVisibility(View.VISIBLE);
} else {
}
//super.onPostExecute(param);
}
@Override
protected void onPreExecute() {
feedLoader.setVisibility(View.VISIBLE);
feedContainer.setVisibility(View.GONE);
}
}
}
答案 0 :(得分:1)
实施View.OnClickListener
是不够的。对于要从中接收点击事件的所有视图,您需要使用setOnClickListener()
注册侦听器。
答案 1 :(得分:1)
如果你想说&#34; Button1 &#34;触发setOnClickListener然后添加此行Button1.setOnClickListener(this);
。
这样当单击Button1时,它将触发onClick方法