下面列出了怎么用android.view.View的API类实例代码及写法,或者点击链接到github查看源代码。
public void doSave(View view) {
log("doSave");
boolean syncEnabled = checked(R.id.cbxEnablePolling);
if(syncEnabled) {
boolean hasErrors = requiredFieldsMissing();
hasErrors |= illegalCharsInTextfields();
if(hasErrors) return;
}
submitButton().setEnabled(false);
cancelButton().setEnabled(false);
if(syncEnabled) {
verifyAndSave();
} else saveWithoutVerification();
}
/**
* Retrieves the view in the list corresponding to itemID
*/
public View getViewForID(long itemID) {
int size = getChildCount();
int position = getFirstVisiblePosition();
StableArrayAdapter adapter = ((StableArrayAdapter) getAdapter());
for (int i = 0; i < size; i++) {
if (itemID == adapter.getItemId(position)) {
return getChildAt(i);
}
position++;
}
return null;
}
private void setActionBarTitle(String actionBarTitle) {
this.getSupportActionBar().setDisplayShowCustomEnabled(true);
this.getSupportActionBar().setDisplayShowTitleEnabled(false);
LayoutInflater inflator = LayoutInflater.from(this);
View v = inflator.inflate(R.layout.example_action_bar_own_font, null);
Typeface tf = Typeface.createFromAsset(getAssets(),"font/BlackwoodCastle.ttf");
TextView title1 = (TextView)v.findViewById(R.id.titleFragment1);
title1.setTypeface(tf);
TextView title2 = (TextView)v.findViewById(R.id.titleFragment2);
title2.setTypeface(tf);
int split = (actionBarTitle.length() / 2);
title1.setText(actionBarTitle.substring(0, split));
title2.setText(actionBarTitle.substring(split));
//assign the view to the actionbar
this.getSupportActionBar().setCustomView(v);
}
/**
* 选择普通模式
*/
public void initVideo() {
//外部辅助的旋转,帮助全屏
orientationUtils = new OrientationUtils(this, getGSYVideoPlayer(), getOrientationOption());
//初始化不打开外部的旋转
orientationUtils.setEnable(false);
if (getGSYVideoPlayer().getFullscreenButton() != null) {
getGSYVideoPlayer().getFullscreenButton().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showFull();
clickForFullScreen();
}
});
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.recycle_view, container, false);
recyclerView=(BaseRecycleView)view.findViewById(R.id.recycle_view);
list=new ArrayList<>();
list.add(new HobbyArray(1,"",1,1));
list.add(new HobbyArray(1,"",1,1));
list.add(new HobbyArray(1,"",1,1));
adapter=new MyAdapter();
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
TextView empty=(TextView)view.findViewById(R.id.empty_view);
empty.setText("似乎没什么感兴趣的呢");
recyclerView.setEmptyView(empty);
recyclerView.setAdapter(adapter);
return view;
}
public static int statusBarLightMode(final Activity activity) {
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (MIUISetStatusBarLightMode(activity.getWindow(), true)) {
result = 1;
} else if (FlymeSetStatusBarLightMode(activity.getWindow(), true)) {
result = 2;
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
activity.getWindow()
.getDecorView()
.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
result = 3;
}
}
return result;
}
@SuppressWarnings("ResourceType")
private static void restoredFromSaved(View v, Field f, UiElement element, Bundle bundle) {
if (bundle != null) {
if (v != null) {
final String elementKey = getElementKey(element);
if (isFieldInBundle(elementKey, bundle)) {
v.setVisibility(bundle.getInt(elementKey + "_visibility"));
v.setEnabled(bundle.getBoolean(elementKey + "_enabled"));
if (v instanceof TextView) {
((TextView)v).setText(bundle.getString(elementKey + "_text"));
}
}
} else {
Log.d("loadFields", "NullPointerException when trying to find view with id: " +
element.value() + ", element is: " + f + " (" + f.getName() + ")");
}
}
}
protected static void setOriginalSharedElementState(ArrayList<View> sharedElements,
ArrayList<SharedElementOriginalState> originalState) {
for (int i = 0; i < originalState.size(); i++) {
View view = sharedElements.get(i);
SharedElementOriginalState state = originalState.get(i);
if (view instanceof ImageView && state.mScaleType != null) {
ImageView imageView = (ImageView) view;
imageView.setScaleType(state.mScaleType);
if (state.mScaleType == ImageView.ScaleType.MATRIX) {
imageView.setImageMatrix(state.mMatrix);
}
}
view.setElevation(state.mElevation);
view.setTranslationZ(state.mTranslationZ);
int widthSpec = View.MeasureSpec.makeMeasureSpec(state.mMeasuredWidth,
View.MeasureSpec.EXACTLY);
int heightSpec = View.MeasureSpec.makeMeasureSpec(state.mMeasuredHeight,
View.MeasureSpec.EXACTLY);
view.measure(widthSpec, heightSpec);
view.layout(state.mLeft, state.mTop, state.mRight, state.mBottom);
}
}
private void b(Context context, ViewGroup viewgroup)
{
h = new View(context);
android.widget.FrameLayout.LayoutParams layoutparams;
if (b.isNavigationAtBottom())
{
layoutparams = new android.widget.FrameLayout.LayoutParams(-1, b.getNavigationBarHeight());
layoutparams.gravity = 80;
} else
{
layoutparams = new android.widget.FrameLayout.LayoutParams(b.getNavigationBarWidth(), -1);
layoutparams.gravity = 5;
}
h.setLayoutParams(layoutparams);
h.setBackgroundColor(0x99000000);
h.setVisibility(8);
viewgroup.addView(h);
}
private AlertDialog createNotebookDialog(Intent startActivity){
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(R.string.dialog_input_text_notebook);
LayoutInflater inflater = activity.getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_text_input, null);
builder.setView(view);
builder.setPositiveButton(R.string.ok,new CreateNotebookButtonListener(startActivity, (EditText)view.findViewById(R.id.dialog_text_input_field)));
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//nothing
}
});
return builder.create();
}
private void initAppList(final boolean isFilter) {
new Thread() {
@Override
public void run() {
super.run();
//扫描得到APP列表
final List<MyAppInfo> appInfos = ApkTool.scanLocalInstallAppList(AppsActivity.this.getPackageManager(), isFilter);
mHandler.post(new Runnable() {
@Override
public void run() {
mAppAdapter.setData(appInfos);
runOnUiThread(new Runnable() {
@Override
public void run() {
mProgressBar.setVisibility(View.GONE);
}
});
}
});
}
}.start();
}
private BookmarkDialog(Context context, @NonNull BookmarkBean bookmarkBean, boolean isAdd) {
super(context, R.style.alertDialogTheme);
this.context = context;
this.bookmarkBean = bookmarkBean;
@SuppressLint("InflateParams") View view = LayoutInflater.from(context).inflate(R.layout.dialog_bookmark, null);
bindView(view);
setContentView(view);
tvChapterName.setText(bookmarkBean.getChapterName());
tvContent.setText(bookmarkBean.getContent());
if (isAdd) {
llEdit.setVisibility(View.GONE);
tvOk.setVisibility(View.VISIBLE);
} else {
llEdit.setVisibility(View.VISIBLE);
tvOk.setVisibility(View.GONE);
}
}
@Override
public BaseDialogFragment.Builder build(BaseDialogFragment.Builder builder) {
TextView message = new TextView(getActivity());
message.setText(getString(R.string.login_error));
Linkify.addLinks(message, Linkify.ALL);
int padding = (int) getActivity().getResources()
.getDimension(R.dimen.dialog_message_padding);
builder.setView(message, padding, padding, padding, padding);
builder.setTitle(getString(R.string.hmm));
builder.setNegativeButton(getString(android.R.string.ok), new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
return builder;
}
@Test
public void shouldSearchInvalidUsername() {
String username = "invalidUsername";
TextView textView = new TextView(application);
textView.setText(username);
HttpException mockHttpException =
new HttpException(Response.error(404, mock(ResponseBody.class)));
when(githubService.publicRepositories(username))
.thenReturn(Observable.<List<Repository>>error(mockHttpException));
mainViewModel.onSearchAction(textView, EditorInfo.IME_ACTION_SEARCH, null);
verify(dataListener, never()).onRepositoriesChanged(anyListOf(Repository.class));
assertEquals(mainViewModel.infoMessage.get(),
application.getString(R.string.error_username_not_found));
assertEquals(mainViewModel.infoMessageVisibility.get(), View.VISIBLE);
assertEquals(mainViewModel.progressVisibility.get(), View.INVISIBLE);
assertEquals(mainViewModel.recyclerViewVisibility.get(), View.INVISIBLE);
}
@Override
public void onViewClick(View v) {
int vId = v.getId();
switch (vId) {
case R.id.tv_right:
case R.id.iv_send:
String old_pwd = et_old_pwd.getText().toString();
String new_pwd = et_new_pwd.getText().toString();
String new_pwd_2 = et_new_pwd_2.getText().toString();
if (TextUtils.isEmpty(old_pwd) || TextUtils.isEmpty(new_pwd) || TextUtils.isEmpty(new_pwd_2)) {
ZToastUtils.toastMessage(mContext, R.string.z_toast_input_not_null);
return;
}
if (!new_pwd.equals(new_pwd_2)) {
ZToastUtils.toastMessage(mContext, R.string.z_toast_pwd_not_same);
return;
}
if (old_pwd.equals(new_pwd)) {
//TODO
return;
}
sendEdit(new_pwd);
break;
}
}
private void noNetworkConnection() {
titleTextView.setText(R.string.no_network_connection);
messageTextView.setText(Html.fromHtml(getString(R.string.wizard_search_no_network_connection)));
messageTextView.setMovementMethod(LinkMovementMethod.getInstance());
progressBar.setVisibility(View.GONE);
hostListGridView.setVisibility(View.GONE);
nextButton.setVisibility(View.GONE);
previousButton.setVisibility(View.VISIBLE);
previousButton.setText(R.string.search_again);
previousButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSearching();
}
});
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.transport_selection_list_item, parent, false);
}
TransportOption transport = (TransportOption) getItem(position);
ImageView imageView = ViewUtil.findById(convertView, R.id.icon);
TextView textView = ViewUtil.findById(convertView, R.id.text);
TextView subtextView = ViewUtil.findById(convertView, R.id.subtext);
imageView.getBackground().setColorFilter(transport.getBackgroundColor(), Mode.MULTIPLY);
imageView.setImageResource(transport.getDrawable());
textView.setText(transport.getDescription());
if (transport.getSimName().isPresent()) {
subtextView.setText(transport.getSimName().get());
subtextView.setVisibility(View.VISIBLE);
} else {
subtextView.setVisibility(View.GONE);
}
return convertView;
}
public void bind(final MenuOption option, final OnNavigationClick onNavigationClick) {
textView.setText(option.text);
imageView.setImageResource(option.icon);
itemView.setSelected(selectedItem == getLayoutPosition());
if (option.id.equals("new")) {
divider.setVisibility(View.VISIBLE);
} else {
divider.setVisibility(View.INVISIBLE);
}
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
//only change selection if we are switching accounts
notifyItemChanged(selectedItem);
if (!option.id.equals("new") && !option.id.equals("settings")) {
selectedItem = getLayoutPosition();
notifyItemChanged(selectedItem);
}
onNavigationClick.onClick(option.id);
}
};
itemView.setOnClickListener(onClickListener);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.iv_back:
finish();
break;
case R.id.iv_finish:
String slognName = mUsercenterSign.getText().toString();
if (slognName != null && slognName.length() > 0) {
Toast.makeText(IndividualityActivity.this, slognName, Toast.LENGTH_SHORT).show();
KeyBoard.closeSoftKeyboard(IndividualityActivity.this);
PreferencesUtils.saveSlognName(IndividualityActivity.this, slognName);
Intent intent = new Intent();
setResult(100, intent);
new Handler().postDelayed(() -> finish(), 500);
}
break;
}
}
private void changeStatusBarColor(boolean isFirm) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
int statusBarHeight = getStatusBarHeight(BaseApplication.getContext());
View view = new View(this);
view.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
view.getLayoutParams().height = statusBarHeight;
((ViewGroup) w.getDecorView()).addView(view);
if (isFirm) view.setBackground(getResources().getDrawable(R.color.colorPrimaryDark));
else view.setBackground(getResources().getDrawable(R.color.login_simulation_hint));
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
if (isFirm)
window.setStatusBarColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
else
window.setStatusBarColor(ContextCompat.getColor(this, R.color.login_simulation_hint));
}
}
@Override
protected void onLayout(boolean b, int i, int i1, int i2, int i3)
{
int childCount = getChildCount();
for (int index = 0; index < childCount; index++)
{
View childrenView = getChildAt(index);
int rowNum = index / mColumnCount;
int columnNum = index % mColumnCount;
int left = (mImageWidth + mSpaceSize) * columnNum + getPaddingLeft();
int top = (mImageHeight + mSpaceSize) * rowNum + getPaddingTop();
int right = left + mImageWidth;
int bottom = top + mImageHeight;
childrenView.layout(left, top, right, bottom);
}
}
@Override
public boolean onLongClick(View view) {
if (view == mDefaultActivityButton) {
if (mAdapter.getCount() > 0) {
mIsSelectingDefaultActivity = true;
showPopupUnchecked(mInitialActivityCount);
}
} else {
throw new IllegalArgumentException();
}
return true;
}
@Override
void getLaneForChild(LaneInfo outInfo, View child, Direction direction) {
super.getLaneForChild(outInfo, child, direction);
if (outInfo.isUndefined()) {
getLanes().findLane(outInfo, getLaneSpanForChild(child), direction);
}
}
@Override
public <V extends View> BinderViewHolder<BaseCell, V> createViewHolder(@NonNull ControlBinder<BaseCell, V> binder,
@NonNull Context context, ViewGroup parent,
String cellType) {
V view;
if (binder != null) {
view = binder.createView(context, parent, mMvHelper.renderManager().getComponentInfo(cellType));
} else {
view = (V) new Space(context);
}
return new BinderViewHolder<>(view, binder);
}
/**
* Open the specified drawer by animating it out of view.
*
* @param gravity Gravity.LEFT to move the left drawer or Gravity.RIGHT for the right.
* GravityCompat.START or GravityCompat.END may also be used.
*/
public void openDrawer(@EdgeGravity int gravity) {
final View drawerView = findDrawerWithGravity(gravity);
if (drawerView == null) {
throw new IllegalArgumentException("No drawer view found with gravity " +
gravityToString(gravity));
}
openDrawer(drawerView);
}
private VerticalGridView findFirstGrid(ViewGroup container) {
for (int i = 0, k = container.getChildCount(); i < k; i++) {
View view = container.getChildAt(i);
if (view instanceof VerticalGridView) {
return (VerticalGridView) view;
}
}
return null;
}
private void clear() {
equalBtn.setVisibility(View.GONE);
submitBtn.setVisibility(View.VISIBLE);
firstValue = null;
secondsValue = null;
operatorExecute = Operators.NONE;
prevOperatorExecute = Operators.NONE;
developmentOperationInputText.setText("");
inputNumberText.setText("");
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.card_select_value, parent);
}
final TextView view = (TextView) convertView.findViewById(R.id.value);
view.setText(String.format("%02d", position));
return convertView;
}
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this,itemView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// send selected contact in callback
listener.onAccountSelected(accounts.get(getAdapterPosition()));
}
});
}
@Override
public void onScrollDown(float nextTranslation) {
final int measuredHeight = topBar.getMeasuredHeight();
if (topBar.getVisibility() == View.GONE && nextTranslation > -measuredHeight) {
topBar.setVisibility(View.VISIBLE);
topBar.setTranslationY(nextTranslation);
} else if (nextTranslation <= 0 && nextTranslation >= -measuredHeight) {
topBar.setTranslationY(nextTranslation);
}
}
如果文章对你有帮助,欢迎点击上方按钮打赏作者